package com.beemans.topon.demo.ui.adapters

import androidx.core.view.isVisible
import androidx.lifecycle.LifecycleOwner
import com.beemans.common.ext.addMultiTypeDelegate
import com.beemans.topon.demo.R
import com.beemans.topon.demo.data.NativeAdListEntity
import com.beemans.topon.demo.helper.NativeAdListHelper
import com.chad.library.adapter.base.BaseDelegateMultiAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder

/**
 * @author ti
 * @date 2022/11/23.
 */
class NativeAdListAdapter(private val owner: LifecycleOwner) :
    BaseDelegateMultiAdapter<NativeAdListEntity, BaseViewHolder>() {
    private val adListHelper by lazy {
        NativeAdListHelper(
            owner,
            R.id.nativeAdList_flAd,
            R.id.nativeAdList_viewSelfRender
        )
    }

    companion object {
        const val TYPE_CONTENT = 0
        const val TYPE_AD = 1
    }

    init {
        addMultiTypeDelegate { it.itemViewType }?.let {
            it.addItemType(TYPE_CONTENT, R.layout.item_native_ad_list_content)
            it.addItemType(TYPE_AD, R.layout.item_native_ad_list)
        }
    }

    override fun convert(holder: BaseViewHolder, item: NativeAdListEntity) {
        when (item.itemViewType) {
            TYPE_CONTENT -> {
            }
            TYPE_AD -> {
                itemViewVisible(holder, isVisible = false)
                adListHelper.loadAd(holder) { viewHolder, isVisible ->
                    itemViewVisible(viewHolder, isVisible = isVisible)
                }
            }
        }
    }

    private fun itemViewVisible(holder: BaseViewHolder, isVisible: Boolean) {
        holder.itemView.isVisible = isVisible
        val size = if (isVisible) -2 else 0
        holder.itemView.layoutParams = holder.itemView.layoutParams.apply {
            width = size
            height = size
        }
    }

    override fun onViewDetachedFromWindow(holder: BaseViewHolder) {
        super.onViewDetachedFromWindow(holder)
        if (holder.itemViewType == TYPE_AD) {
            adListHelper.removeHolder(holder)
        }
    }
}